/***
 *   @title qz
 *   @description <description class purpose>
 *   @author yichen
 *   @version 1.0.0
 *   @create 2023/9/25 0025
 **/
package io.gitee.wokaixin.yunque.driver;

import io.lettuce.core.codec.*;
import io.lettuce.core.internal.*;
import io.netty.buffer.*;
import io.netty.util.*;

import java.nio.*;
import java.nio.charset.*;
//格式化 key string value byte[]
public class StringByteArrayCodec implements RedisCodec<String, byte[]>, ToByteBufEncoder<String, byte[]> {
    public static final StringCodec UTF8 = new StringCodec(StandardCharsets.UTF_8);

    public static final StringCodec ASCII = new StringCodec(StandardCharsets.US_ASCII);
    public static final ByteArrayCodec INSTANCE = new ByteArrayCodec();

    private static final byte[] EMPTY = new byte[0];
    private final Charset charset;

    private final float averageBytesPerChar;

    private final float maxBytesPerChar;

    private final boolean ascii;

    private final boolean utf8;

    /**
     * Creates a new {@link StringCodec} with the default {@link Charset#defaultCharset() charset}. The default is determined
     * from the {@code file.encoding} system property.
     */
    public StringByteArrayCodec() {
        this(Charset.defaultCharset());
    }

    /**
     * Creates a new {@link StringCodec} for the given {@link Charset} that encodes and decodes keys and values.
     *
     * @param charset must not be {@code null}.
     */
    public StringByteArrayCodec(Charset charset) {

        LettuceAssert.notNull(charset, "Charset must not be null");

        this.charset = charset;

        CharsetEncoder encoder = CharsetUtil.encoder(charset);
        this.averageBytesPerChar = encoder.averageBytesPerChar();
        this.maxBytesPerChar = encoder.maxBytesPerChar();

        if (charset.name().equals("UTF-8")) {
            utf8 = true;
            ascii = false;
        } else if (charset.name().contains("ASCII")) {
            utf8 = false;
            ascii = true;
        } else {
            ascii = false;
            utf8 = false;
        }
    }

    @Override
    public void encodeKey(String key, ByteBuf target) {

        if (key != null) {
            encode(key, target);
        }
    }

    @Override
    public void encodeValue(byte[] value, ByteBuf target) {

        if (value != null) {
            target.writeBytes(value);
        }
    }


    @Override
    public int estimateSize(Object keyOrValue) {

        if (keyOrValue instanceof String) {
            return sizeOf((String) keyOrValue, true);
        }else if (keyOrValue instanceof Byte[]){
            return ((byte[]) keyOrValue).length;
        }
        return 0;
    }

    @Override
    public String decodeKey(ByteBuffer bytes) {

        return Unpooled.wrappedBuffer(bytes).toString();
    }

    @Override
    public byte[] decodeValue(ByteBuffer bytes) {
        return getBytes(bytes);
    }

    /**
     * Calculate either the maximum number of bytes a string may occupy in a given character set or
     * the average number of bytes it may hold.
     */
    int sizeOf(String value, boolean estimate) {

        if (utf8) {
            return ByteBufUtil.utf8MaxBytes(value);
        }

        if (ascii) {
            return value.length();
        }

        if (estimate) {
            return (int) averageBytesPerChar * value.length();
        }

        return (int) maxBytesPerChar * value.length();
    }
    public void encode(String str, ByteBuf target) {

        if (str == null) {
            return;
        }

        if (utf8) {
            ByteBufUtil.writeUtf8(target, str);
            return;
        }

        if (ascii) {
            ByteBufUtil.writeAscii(target, str);
            return;
        }

        CharsetEncoder encoder = CharsetUtil.encoder(charset);
        int length = sizeOf(str, false);
        target.ensureWritable(length);

        try {
            ByteBuffer dstBuf = target.nioBuffer(0, length);
            int pos = dstBuf.position();

            CoderResult cr = encoder.encode(CharBuffer.wrap(str), dstBuf, true);
            if (!cr.isUnderflow()) {
                cr.throwException();
            }
            cr = encoder.flush(dstBuf);
            if (!cr.isUnderflow()) {
                cr.throwException();
            }
            target.writerIndex(target.writerIndex() + dstBuf.position() - pos);
        } catch (CharacterCodingException x) {
            throw new IllegalStateException(x);
        }
    }
    /**
     * Compatibility implementation.
     *
     * @param key
     * @return
     */
    private ByteBuffer encodeAndAllocateBuffer(String key) {

        if (key == null) {
            return ByteBuffer.wrap(EMPTY);
        }

        ByteBuffer buffer = ByteBuffer.allocate(sizeOf(key, false));

        ByteBuf byteBuf = Unpooled.wrappedBuffer(buffer);
        byteBuf.clear();
        encode(key, byteBuf);
        buffer.limit(byteBuf.writerIndex());

        return buffer;
    }
    @Override
    public ByteBuffer encodeKey(String key) {
        if (key == null) {
            return ByteBuffer.wrap(EMPTY);
        }

        return encodeAndAllocateBuffer(key);
    }


    @Override
    public ByteBuffer encodeValue(byte[] value) {
        return ByteBuffer.wrap(value);
    }

    private static byte[] getBytes(ByteBuffer buffer) {

        int remaining = buffer.remaining();

        if (remaining == 0) {
            return EMPTY;
        }

        byte[] b = new byte[remaining];
        buffer.get(b);
        return b;
    }

}
